package com.summer.core.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class JavaGenUtil {

	public static void writeFile(String packageName) throws ClassNotFoundException {
		
		List<String> classNames = getClassName(packageName);
		for (String className : classNames) {
			Class clazz = Class.forName(className);
			Field[] field = clazz.getDeclaredFields();
			Set<String> fieldTypes = new HashSet<String>();
			for (int i = 0; i < field.length; i++) {
				fieldTypes.add(field[i].getType().getName());
			}
			StringBuffer res = new StringBuffer();
			res.append("package " + packageName + ";").append("\n").append("\n");
			for (String fieldType : fieldTypes) {
				if(!fieldType.contains(".")) {
					continue;
				}
				res.append("import " + fieldType + ";").append("\n");
			}
			res.append("import java.io.Serializable;").append("\n");
			
			res.append("import javax.persistence.Column;").append("\n");
			res.append("import javax.persistence.Entity;").append("\n");
			res.append("import javax.persistence.Id;").append("\n");
			res.append("import javax.persistence.Table;").append("\n");
			
			res.append("\n").append("\n");
			StringBuffer head = new StringBuffer();
			head.append("@Entity").append("\n");
			head.append("@Table(name = \"");
			for (int j = 0; j < clazz.getSimpleName().length(); j++) {
				if (Character.isUpperCase(clazz.getSimpleName().charAt(j))) {
					if (j != 0) {
						head.append("_");
					}
					head.append((clazz.getSimpleName().charAt(j)+"").toLowerCase());
					
				} else {
					head.append(clazz.getSimpleName().charAt(j));
				}
			}
			head.append("\")");
			res.append(head).append("\n");
			res.append("public class " + clazz.getSimpleName()).append(" implements Serializable {").append("\n");
			StringBuffer fieldArea = new StringBuffer();
			for (int i = 0; i < field.length; i++) {
				String prefix = "private ";
				String suffix = ";\n";
				if (field[i].getName().equals("serialVersionUID")) {
					prefix = "private static final ";
					suffix = " = 1L;\n";
				}
				fieldArea.append("\t" + prefix + field[i].getType().getSimpleName() + " " + field[i].getName()).append(suffix);
			}
			res.append(fieldArea);
			for (int i = 0; i < field.length; i++) {
				
				String name = field[i].getName();
				if (name.equals("serialVersionUID")) {
					continue;
				}
				if (name.equals("id")) {
					res.append("\t@Id").append("\n");
				}
				String type = field[i].getType().getName().replace("java.util.", "").replace("java.lang.", "");
				res.append("\t@Column(name = \"");
				StringBuffer get = new StringBuffer();
				StringBuffer set = new StringBuffer();
				get.append("\tpublic " + type + " get");
				set.append("\tpublic void set");
				
				for (int j = 0; j < name.length(); j++) {
					if (j == 0) {
						get.append((name.charAt(j)+"").toUpperCase());
						set.append((name.charAt(j)+"").toUpperCase());
					} else {
						get.append(name.charAt(j));
						set.append(name.charAt(j));
					}
					if (Character.isUpperCase(name.charAt(j))) {
						res.append("_");
						res.append((name.charAt(j)+"").toLowerCase());
						
					} else {
						res.append(name.charAt(j));
					}
				}
				res.append("\"");
				if (name.equals("id")) {
					res.append(", nullable =  false, unique = true, length = 50");
				}
				res.append(")");
				res.append("\n");
				get.append("() {");
				set.append("(" + type + " " + name + ") {");
				get.append("\n");
				set.append("\n");
				get.append("\t\treturn this." + name + ";");
				set.append("\t\tthis." + name + " = " + name + ";");
				get.append("\n");
				set.append("\n");
				get.append("\t}");
				set.append("\t}");
				res.append(get);
				res.append("\n");
				res.append(set);
				res.append("\n");
				
			}
			res.append("}");
			write(res.toString(), clazz.getSimpleName());
		}

		
		
	}
	
	public static void write(String content, String fileName) {  
		 String filePath = "E:\\javaout\\" + fileName + ".java";
		 File file = new File(filePath);
		 if(file.exists()) {
			 file.delete();
			 file = new File(filePath);
		 }
		 
		        FileWriter fwriter = null;
		        try {
		            // true表示不覆盖原来的内容，而是加到文件的后面。若要覆盖原来的内容，直接省略这个参数就好
		            fwriter = new FileWriter(filePath, true);
		            fwriter.write(content);
		        } catch (IOException ex) {
		            ex.printStackTrace();
		        } finally {
		            try {
		                fwriter.flush();
		                fwriter.close();
		            } catch (IOException ex) {
		                ex.printStackTrace();
		            }
		        }
	}
	
	public static List<String> getClassName(String packageName) {
		String filePath = ClassLoader.getSystemResource("").getPath() + packageName.replace(".", "\\");
		List<String> fileNames = getClassName(filePath, null);
		return fileNames;
	}
 
	private static List<String> getClassName(String filePath, List<String> className) {
		List<String> myClassName = new ArrayList<String>();
		File file = new File(filePath);
		File[] childFiles = file.listFiles();
		for (File childFile : childFiles) {
			if (childFile.isDirectory()) {
				myClassName.addAll(getClassName(childFile.getPath(), myClassName));
			} else {
				String childFilePath = childFile.getPath();
				childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf("."));
				childFilePath = childFilePath.replace("\\", ".");
				myClassName.add(childFilePath);
			}
		}
 
		return myClassName;
	}


	public static void main(String[] args) throws ClassNotFoundException {
		writeFile("com.summer.jira.model");
	}
}
